package com.spdg.ring;

import java.io.IOException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
import cn.wolf.base.ICallBack;
import cn.wolf.tools.CommonUtils;
import cn.wolf.tools.StringUtil;

import com.spdg.ring.bo.WeiboBo;
import com.spdg.ring.common.Key;
import com.spdg.ring.widget.AccessTokenKeeper;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

/**
 * <p>Title: 分享微博   </p>
 * <p>Description: 
 * </p>
 * <p>@author: Eric.wsd                </p>
 * <p>Copyright: Copyright (c) 2012    </p>
 * <p>Company: HX Co., Ltd.          </p>
 * <p>Create Time: 2012-11-14             </p>
 * <p>Update Time:                     </p>
 * <p>Updater:                         </p>
 * <p>Update Comments:                 </p>
 */
public class ShareActivity extends RingBaseActivity implements OnClickListener, RequestListener {

	private TextView mTextNum, mTextTitle;
	private View mSend;
	private EditText mEdit;
	private String mContent = "";
	private String mAccessToken = "";
	private String mShareUrl = "";
	private Oauth2AccessToken token;
	private WeiboBo mWeiboBo;

	public static final String EXTRA_WEIBO_CONTENT = "com.weibo.android.content";
	public static final String EXTRA_PIC_URI = "com.weibo.android.pic.uri";
	public static final String EXTRA_ACCESS_TOKEN = "com.weibo.android.accesstoken";
	public static final String EXTRA_EXPIRES_IN = "com.weibo.android.token.expires";

	public static final int WEIBO_MAX_LENGTH = 140;

	@Override
	protected void initComponents() {
		mSend = findViewById(R.id.top_right);
		mSend.setBackgroundResource(R.drawable.btn_send_weibo_bg);
		mSend.setOnClickListener(this);
		mTextTitle = (TextView) findViewById(R.id.top_title);
		View total = findViewById(R.id.weibosdk_ll_text_limit_unit);
		total.setOnClickListener(this);
		mTextNum = (TextView) this.findViewById(R.id.weibosdk_tv_text_limit);

		mEdit = (EditText) this.findViewById(R.id.weibosdk_etEdit);
		mEdit.addTextChangedListener(new OnTextWatcher());
	}

	@Override
	protected void initData() {
		// 设置标题
		mTextTitle.setText(R.string.weibo_share_dialog_title);
		// 获取数据
		Intent i = getIntent();
		mContent = i.getStringExtra(Key.K_WEIBO_SHARE_CONTENT); // 微博内容
		mShareUrl = i.getStringExtra(Key.K_WEIBO_SHARE_URL); // 微博链接

		if (!StringUtil.isEmpty(mShareUrl)) {
			mEdit.setText(mContent + mShareUrl);
		} else {
			mEdit.setText(mContent);
		}
	}

	private void initWeibo() {
		// 初始化微博
		token = AccessTokenKeeper.readAccessToken(mContext);

		mAccessToken = token.getToken();
		if (token != null && token.isSessionValid()) {
			if (mSend instanceof TextView) {
				((TextView) mSend).setText(R.string.weibo_send);
				((TextView) mSend).setGravity(Gravity.CENTER);
			}

		} else {
			if (mSend instanceof TextView) {
				((TextView) mSend).setText(R.string.weibo_auth);
				((TextView) mSend).setGravity(Gravity.CENTER);
			}
		}

		if (mWeiboBo == null)
			mWeiboBo = new WeiboBo(mContext, new WeiboCallBack());
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 初始化微博
		initWeibo();
	}

	@Override
	public void onClick(View v) {
		int viewId = v.getId();

		token = AccessTokenKeeper.readAccessToken(mContext);
		if (token != null)
			mAccessToken = token.getToken();

		if (viewId == R.id.top_right) {
			if (token.isSessionValid()) {
				send();
			} else {
				authorite();
			}

		} else if (viewId == R.id.weibosdk_ll_text_limit_unit) {
			Dialog dialog = new AlertDialog.Builder(this).setTitle(R.string.weibo_attention)
					.setMessage(R.string.weibo_delete_all)
					.setPositiveButton(R.string.weibo_ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							mEdit.setText("");
						}
					}).setNegativeButton(R.string.weibo_cancel, null).create();
			dialog.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (mWeiboBo.mSsoHandler != null) {
			mWeiboBo.mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	/**
	 * 微博认证
	 */
	private void authorite() {
		mWeiboBo.authorize();
	}

	/**
	 * 发送微博
	 */
	private void send() {
		Animation shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);

		StatusesAPI api = new StatusesAPI(token);
		if (!TextUtils.isEmpty(mAccessToken)) {
			this.mContent = mEdit.getText().toString();
			if (TextUtils.isEmpty(mContent)) {
				CommonUtils.showErrorByEditText(mEdit, "请输入内容!", shake);
				return;
			}

			api.update(this.mContent, "90.0", "90.0", this);
		} else {
			CommonUtils.showToast(mContext, getString(R.string.weibo_please_login));
		}
	}

	@Override
	public void onComplete(String response) {
		CommonUtils.showToast(mContext, getString(R.string.weibo_send_sucess));

		finish();
	}

	@Override
	public void onIOException(IOException e) {

	}

	@Override
	public void onError(final WeiboException e) {
		CommonUtils.showToast(mContext, getString(R.string.weibo_auth_exception));
		mWeiboBo.unBindAuthor();
	}

	class WeiboCallBack implements ICallBack {

		@Override
		public void call(String type) {
			if (WeiboBo.TYPE_WEIBO_BIND_SUCCESSFUL.equals(type)) {
				CommonUtils.showToast(mContext, getString(R.string.weibo_auth_ok));
				initWeibo();
			} else if (WeiboBo.TYPE_WEIBO_CANCEL.equals(type)) {
				CommonUtils.showToast(mContext, getString(R.string.weibo_auth_unbind));
			} else if (WeiboBo.TYPE_WEIBO_EXCEPTION.equals(type)) {
				CommonUtils.showToast(mContext, getString(R.string.weibo_auth_exception));
				mWeiboBo.unBindAuthor();
			}
		}
	}

	class OnTextWatcher implements TextWatcher {

		public void afterTextChanged(Editable s) {
		}

		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before, int count) {
			String mText = mEdit.getText().toString();
			int len = mText.length();
			if (len <= WEIBO_MAX_LENGTH) {
				len = WEIBO_MAX_LENGTH - len;
				// mTextNum.setTextColor(R.color.weibosdk_text_num_gray);
				if (!mSend.isEnabled())
					mSend.setEnabled(true);
			} else {
				len = len - WEIBO_MAX_LENGTH;

				mTextNum.setTextColor(Color.RED);
				if (mSend.isEnabled())
					mSend.setEnabled(false);
			}
			mTextNum.setText(String.valueOf(len));
		}
	}

	@Override
	protected String getEventID() {
		return null;
	}

	@Override
	protected int getMainContentViewId() {
		return R.layout.act_share_weibo;
	}

	@Override
	protected Class<?> getResouceClass() {
		return R.class;
	}

}
